class RequirementOrder < ActiveRecord::Base
  belongs_to :user
  belongs_to :requirement
  
  def self.exists?(u,r)
    not find_by_user_id_and_requirement_id(u,r).nil?
  end
  
  def self.confirm_user(u,r)
    unless u.role==DEMANDER or RequirementOrder.exists?(u,r)
      transaction do
        create(:user => u, :requirement => r)
        r.update_attribute(:status,"ordered")
      end
    end
  end
  
  def self.break_user(u,r)
    transaction do
      destroy(find_by_user_id_and_requirement_id(u,r))
      r.update_attribute(:status,"begined") if r.orders.length==0
    end
  end
end
